package com.group525.cloudef.service.doctor.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.group525.cloudef.Dao.doctor.DiagnoseDao;
import com.group525.cloudef.Dao.doctor.UserInfo;
import com.group525.cloudef.Dao.doctor.reportRecord;
import com.group525.cloudef.common.CommonResult;
import com.group525.cloudef.entity.doctor.DUser;
import com.group525.cloudef.entity.user.*;
import com.group525.cloudef.mapper.doctor.DUserMapper;
import com.group525.cloudef.mapper.doctor.DdiagnoseMapper;
import com.group525.cloudef.service.doctor.DUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.group525.cloudef.utils.Log;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author group525
 * @since 2023-04-19
 */
@Service
public class DUserServiceImpl extends ServiceImpl<DUserMapper, DUser> implements DUserService {

    @Resource
    DUserMapper DuserMapper;
    @Resource
    DdiagnoseMapper diagnoseMapper;
    @Resource
    Log log;

    @Override
    public CommonResult<?> login(DUser doc) {
        //1.获取输入的ID与password
        String jobNumber = doc.getJobNumber();
        String InputPassword = doc.getPassword();
        //2.从表中查询ID和密码是否匹配
        DUser login = DuserMapper.login(jobNumber);
        if (login != null) {
            String Password = login.getPassword();
            log.debug("in:", InputPassword);
            log.debug("o:", jobNumber);
            if (InputPassword.equals(Password)) {
                return CommonResult.success("登录成功", login);
            }
            return CommonResult.failed("密码错误");
        }
        return CommonResult.failed("用户不存在");
    }

    @Override
    public List<DUser> getDoctors(String area, String buwei) {

        if(Objects.equals(area, "全国") && Objects.equals(buwei, "全部部位")){
            return DuserMapper.selectList(null);
        }
        if(Objects.equals(area, "全国") && !Objects.equals(buwei, "全部部位")){
            QueryWrapper<DUser>queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("GoodAt",buwei);
            return DuserMapper.selectList(queryWrapper);
        }
        if(!Objects.equals(area, "全国") && Objects.equals(buwei, "全部部位")){
            QueryWrapper<DUser>queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("area",area);
            return DuserMapper.selectList(queryWrapper);
        }
        if(!Objects.equals(area, "全国") && !Objects.equals(buwei, "全部部位")){
            QueryWrapper<DUser>queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("area",area).eq("GoodAt",buwei);
            return DuserMapper.selectList(queryWrapper);
        }
        return null;
    }

    public UserInfo info(String jobNum){
        return DuserMapper.info(jobNum);
    }

    @Override
    public CommonResult<?> uploadAvatar(MultipartFile file, HttpServletRequest httpServletRequest) {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tPZ77G575aWGG2e2cb6";
        String accessKeySecret = "2mv4HFqhyc61fzORZB3N4tYxsrc0F0";
        // 填写Bucket名称。
        String bucketName ="blog-avatar";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            InputStream inputStream = file.getInputStream();


            String objectName ="Avatar_";
            //看看是否存过头像
            boolean found = ossClient.doesObjectExist(bucketName, objectName);
            //存过就删除之前的头像
            if(found){
                ossClient.deleteObject(bucketName, objectName);
            }
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, inputStream);
            ossClient.shutdown();

            String url="https://"+bucketName+"."+endpoint+"/"+objectName;

            //存入数据库

//            User user = userMapper.selectById(userId);
//            user.setAvatar(url);
//            int i = userMapper.updateById(user);
//            System.out.println(">>>>>>>>>>>>>>>>>"+i);


            return CommonResult.success("上传成功",url);

        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed();

        }

    }
    @Override
    public List<DiagnoseDao> getPatient(Long doctor_id) {
        //1.从医患关系表选择医生负责的患者（docId、未处理：tag=0）
        List<DiagnoseDao> patientList = diagnoseMapper.getPatientId(doctor_id);
        //2.遍历此时患者List的每一行
        patientList.forEach(DiagnoseDao -> {
            //3.获取患者List每一行的患者ID
            Long userId = DiagnoseDao.getUserId();
            //4.根据UserID从患者表中 拉取对应患者的信息
            DiagnoseDao patientInfo;
            patientInfo = diagnoseMapper.getPatient(userId);
            //5.将患者信息赋予 此时患者List中的信息字段
            DiagnoseDao.setName(patientInfo.getName());
            DiagnoseDao.setGender(patientInfo.getGender());
            DiagnoseDao.setAge(patientInfo.getAge());
        });
        log.debug("ListTest:",patientList);
        return patientList;
    }
    @Override
    public CommonResult<?> createInfectious(Uinfectious uinfectious){
        Date now = new Date();
        uinfectious.setReport_time(now);
        Integer id = diagnoseMapper.getInfectiousCount()+1;
        uinfectious.setId(id);
        log.debug("@@:",uinfectious);
        Integer num = diagnoseMapper.createInfectious(uinfectious);
        if (num==0)
            return CommonResult.failed("提交失败!");
        else
            return CommonResult.success("传染病报告提交成功！");
    }
    @Override
    public CommonResult<?> submitHazard(UHazard uHazard){
        Date now = new Date();
        uHazard.setTime(now);
        Integer no = diagnoseMapper.getHazardCount()+1;
        uHazard.setNo(no);
        log.debug("@@:",uHazard);
        Integer num = diagnoseMapper.submitHazard(uHazard);
        if (num==0)
            return CommonResult.failed("提交失败!");
        else
            return CommonResult.success("危急值报告提交成功！");
    }
    @Override
    public CommonResult<?> submitReport(UReport uReport){
        Date now = new Date();
        uReport.setCreateTime(now);
        uReport.setUpdateTime(now);
        Long no = diagnoseMapper.getReportNo()+1;
        uReport.setReportNo(no);
        log.debug("@@:",uReport);
        Integer num = diagnoseMapper.submitReport(uReport);
        if (num==0)
            return CommonResult.failed("提交失败!");
        else{
            diagnoseMapper.imageAddReport(no, uReport.getUserId());
            diagnoseMapper.updateRelate(uReport.getUserId(), uReport.getDoctorId());
            return CommonResult.success("诊断报告提交成功！");
        }
    }

    @Override
    public List<reportRecord> reportList(){
        List<UReport> report = DuserMapper.reportList();
        List<reportRecord> reportList = new ArrayList<>();
        report.forEach(UReport -> {
            reportRecord record = new reportRecord();
            BeanUtils.copyProperties(UReport,record);

            Long patientId = UReport.getUserId();
            Long doctorId = UReport.getDoctorId();
            record.setDoctorName(DuserMapper.getDocName(doctorId));
            record.setPatientName(DuserMapper.getPatientName(patientId));
            record.setGender(DuserMapper.getPatientGender(patientId));
            record.setAge(DuserMapper.getPatientAge(patientId));
            reportList.add(record);
        });
        return reportList;
    }
    @Override
    public UReport getDiseaseInfo(Long reportNo){
        return DuserMapper.getDiseaseInfo(reportNo);
    }
    @Override
    public List<UImage> getImage(Long reportNo){
        return DuserMapper.getImage(reportNo);
    }
    @Override
    public CommonResult<?> updateReport(UReport uReport){
        String diseaseName = uReport.getDiseaseName();
        String checkIntro = uReport.getCheckIntro();
        String imageInfo = uReport.getImageInfo();
        String diagnose = uReport.getDiagnose();
        Date now = new Date();
        Long reportNo = uReport.getReportNo();
        Integer num = DuserMapper.updateReport(diseaseName, checkIntro, imageInfo, diagnose, now, reportNo);
        if (num==0)
            return CommonResult.failed("提交失败!");
        else
            return CommonResult.success("订正成功！");
    }

    @Override
    public List<String> getTitle() {
        return DuserMapper.getTitle();
    }
    @Override
    public String getContent(String title) {
        return DuserMapper.getContent(title);
    }
}
